package com.gy.boot.controller;

import com.gy.boot.common.aspect.Log;
import com.gy.boot.common.dao.IDao;
import com.gy.boot.common.dao.IEntity;
import com.gy.boot.common.dao.SqlAccess;
import com.gy.boot.common.dao.SqlID;
import com.gy.boot.common.jwt.JWT;
import com.gy.boot.common.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@RestController
@RequestMapping("login")
public class LoginController {

    /**
     * 模拟普通用户登录
     * */
    @GetMapping("login")
    public R login(HttpServletRequest request, HttpServletResponse response, Long id) {
        id = id == null ? 1L : id;
        String token = JWT.createToken(id, 2);
        List<IEntity> listSqlAccess = IDao.listS(SqlID.SqlAccess_listSqlAccessCodeByRoleId, 2L);
        request.setAttribute(JWT.USER_ID, id);
        request.setAttribute(JWT.ROLE_ID, 2);
        SqlAccess.setSqlAccess(id, 2, listSqlAccess);
        JWT.setToken(request, response, token);
        return R.ok(token);
    }

    /**
     * 模拟管理员登录
     * */
    @GetMapping("loginAdmin")
    public R loginAdmin(HttpServletRequest request, HttpServletResponse response, Long id, Integer r) {
        r = r == null ? 1 : r; // 角色ID
        id = id == null ? 1L : id;
        String token = JWT.createToken(id, r); // 设置角色ID
        JWT.setToken(request, response, token);
        return R.ok(token);
    }


    @Autowired
    private ApplicationContext applicationContext;

    /**
     * 停机测试
     */
    @Log("停机")
    @GetMapping("shutdown")
    public void shutdown() {
        ConfigurableApplicationContext context = (ConfigurableApplicationContext) applicationContext;
        context.close();
    }

}
